#!/usr/bin/env bash

# drobban@sdfeu

source '../say.sh'

nick="$1"
chan="$2"
arg="${*:3}"
site="${arg// /}"

function get {
    awk -v n="${1}" 'BEGIN { FS=n"\":" }; { split($2,s,",\"");
    gsub(/"/,"",s[1]); gsub(/}/,"",s[1]); print s[1] }' <<< "$report"
}

if [[ -n "$site" && ! "$site" =~ [^[:alpha:],] ]]; then
    url="api.openweathermap.org/data/2.5/weather?q=$site&units=metric&appid=ef4b86aedd2b2645317ac3b7a22e56f4"
    report="$(curl -s "$url")"
    if [[ "$(get 'cod')" = '200' ]]; then
        city="$(get 'name')"
        country="$(get 'country')"
        temp="$(get 'temp')"
        humid="$(get 'humidity')"
        wind="$(get 'speed')"
        cond="$(get 'description')"
        msg="Weather for $city, $country: $temp C, $humid% humidity, $cond, $wind m/s wind"
    else
        msg='The requested location is not in the database or the server is down.'
    fi
else
    chan="$nick"
    msg=(
        'The command !ow prints observations reported to http://openweathermap.org'
        'Argument format: <city name>[, <country code>]'
        'Use ISO 3166-2 country codes: https://en.wikipedia.org/wiki/ISO_3166'
    )
fi

say "$chan" "${msg[@]}"

